
var models = require('../models');
var fs = require('fs');
var userModel = models.userModel;
function Trim(str,is_global){
	var result; 
 	result = str.replace(/(^\s+)|(\s+$)/g,"");
 	if(is_global.toLowerCase()=="g"){
 		result = result.replace(/\s/g,"");
 	}
 	return result;
}
exports.index = function(req,res){
	res.render('index');
}
exports.select = function(req,res){
	res.render('select');
}
exports.test = function(req,res){
	res.render('test');
}
exports.mongo = function(req,res){
	res.render('mongo');
}
exports.upload = function(req,res){
	var tmpPath = req.files.file.path;
	var date = new Date();
	var now = ''+date.getHours()+date.getMinutes()+date.getSeconds();
	var newName = Trim(req.files.file.name,'g');
	var targetPath = 'public/videos/'+req.body.puid+'/'+now+newName;
	fs.exists('public/videos/'+req.body.puid,function(exists){
		if(!exists){
			fs.mkdir('public/videos/'+req.body.puid,function(err){
				if(!err){
					fs.rename(tmpPath,targetPath,function(err){
						if(err){
							console.log(err);
							res.send({'status':'error','messgae':'move file error'});
						}
						else{
							userModel.findOne({'puid':req.body.puid},function(err,user){
								if(err){
									console.log(err);
									res.send({'status':'error','messgae':'connect database error'});
								}
								else{
									if(user){
										user.videos.push('/videos/'+req.body.puid+'/'+now+newName);
										user.save(function(err){
											if(err){
												console.log(err);
												res.send({'status':'error','messgae':'save user error'});
											}
											else{
												res.send({'status':'success'});
											}
										})
									}
									else{
										res.send({'status':'error','messgae':'user not found'});
									}
								}
							})
						}
					})
				}
				else{
					res.send({'status':'error','messgae':'mkdir error'});
				}
			})
		}
		else{
			fs.rename(tmpPath,targetPath,function(err){
				if(err){
					console.log(err);
					res.send({'status':'error','messgae':'move file error'});
				}
				else{
					userModel.findOne({'puid':req.body.puid},function(err,user){
						if(err){
							console.log(err);
							res.send({'status':'error','message':'connect database error'});
						}
						else{
							if(user){
								user.videos.push('/videos/'+req.body.puid+'/'+now+newName);
								user.save(function(err){
									if(err){
										console.log(err);
										res.send({'status':'error','messgae':'save user error'});
									}
									else{
										res.send({'status':'success'});
									}
								})
							}
							else{
								res.send({'status':'error','message':'user not found'});
							}
						}
					})
				}
			})
		}
	})
}